import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
    selector: 'sa-device-record',
    templateUrl: './device-record.component.html',
    styleUrls: ['./device-record.component.css']
})
export class DeviceRecordComponent implements OnInit {
    tableData: any = []; // table的表单数据
    totalCounts: number = 0; //分页总条数
    curPage: number = 1; //分页当前页
    pageSize: number = 10; //内置的分页每页条数
    // 查询参数
    selectedDeviceId: any = ""; // 选中的设备ID
    selectedCarNumber: any = ""; // 选中的车牌号
    selectedCompanyId: any = "";
    selectedCompanyName: any = ""
    startDate: any = ""; // 开始时间
    endDate: any = ""; // 结束时间
    searchKey: any = ""; // 用户的搜索关键字
    questionType: any = "1"

    constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
        activatedRoute.queryParams.subscribe(queryParams => {
        });
    }
    ngOnInit() {
        // this.initDate().then(()=>this.load());
    }
    // 时间选择回调
    dateSelect(time) {
        this.startDate = time.startTime;
        this.endDate = time.endTime;
        this.tableSearch();
    }
    //初始化时间
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							var date = e.date;
							var time = common.getTimeMmss(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						var date = new Date();
                        let time1 = common.getTimeMmss(date);
                        $("#datetimepicker2").val(time1); //当前时间
                        that.endDate = time1;
                        date.setTime(date.getTime() - 7*(60*60*24*1000)); //设置前7天
                        let time2 = common.getTimeMmss(date);
                        $("#datetimepicker1").val(time2);
                        that.startDate = time2;
						resolve();
					});
				}
			);
		})
	}
    // 获取列表数据
    load() {
        let param = {
            "pageSize": this.pageSize,
            "nowPage": this.curPage,
            "parameters": {
                deviceId: this.selectedDeviceId,
                carNumber: this.selectedCarNumber,
                companyId: this.selectedCompanyId,
                companyName: this.selectedCompanyName,
                startTime: this.startDate,
                endTime: this.endDate,
                searchKey: common.stringTrim(this.searchKey),
                questionType : this.questionType
            }
        }
        let reqdata = 'gridPager=' + JSON.stringify(param);
        this.jsonApiService.http("deviceMark/deviceMarkLogList.html", reqdata).subscribe(result => {
            let data = []
            if (result.isSuccess && result.exhibitDatas) {
                for(var i=0;i< result.exhibitDatas.length;i++){
                    result.exhibitDatas[i].isChecked = false;
                }
                data = result.exhibitDatas
                this.tableData = result.exhibitDatas
                this.totalCounts = result.recordCount;
            }
        });
    }
    //Tab 切换
	tabChange(type){
		this.questionType = type;
		this.curPage = 1;
		this.pageSize = 10;
		this.tableData = [];
		this.searchKey = ''
		this.load();
	}
    // 分页回调
    paginate(e) {
        this.tableData = [];
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
    // 刷新表
    refresh() {
        this.load();
    }
    // 表单查询
    tableSearch() {
        this.curPage = 1;
        this.tableData = [];
        this.load();
    }
    //公司选中回调
    companySelected(data) {
		this.selectedDeviceId = data.deviceId;
		this.selectedCarNumber = data.carNumber;
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
    //查看
	ProblemModalTableData : any =[];
	problemName : any =''
	tablelook(type,row,modal){
        this.ProblemModalTableData = [];
		if(type == '1'){
			this.ProblemModalTableData = row;
			this.problemName = '传感器';
		}
		if(type =='2'){
			this.ProblemModalTableData.push(row);
			this.problemName = 'GPS';
		}
		modal.show();
	}
	cancelProblemModal(modal){
		this.ProblemModalTableData = [];
		modal.hide();
    }
    
    // 数据导出
	exportData(){	
		const param = {			
			deviceId: this.selectedDeviceId,
            carNumber: this.selectedCarNumber,
            companyId: this.selectedCompanyId,
            companyName: this.selectedCompanyName,
            startTime: this.startDate,
            endTime: this.endDate,
            searchKey: common.stringTrim(this.searchKey),
            questionType : this.questionType
		}
        let timeCheck = common.correctTime(param, ['questionType'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
        common.exprotDataFile(param, 'param', config.BaseURL + 'deviceMark/exportDeviceMarkLogList.html')	
    }


    abnormalDeviceList: any =[];
    abnormalCarNamber:any;
    abnormalompanyName:any;
    /**
	 *  echart图   异常数据折线图
	 */
    specifyId={
		picker1:'datetimepicker3',
		picker2:'datetimepicker4'
	}
	activeSelected: any;
	startTime_chart: string = '';
	endTime_chart: string = '';
	isChartView: boolean = false;
	isMapView: boolean = false;
	specifyTime: any = {
		startTime: '',
		endTime: ''
	}
	selectedRow: any;
	drawTrackArr: any;
	//数据查看
	drawAbnormalChart() {
		if (!this.selectedRow) {
			this.jsonApiService.message('先选择需要查看折线图的车辆');
			return;
		}
		if (!this.startTime_chart || !this.endTime_chart) {
			this.jsonApiService.message('时间不能为空');
			return;
		}
		let timeCheck = common.correctTimeParams(this.startTime_chart, this.endTime_chart, 0);
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		this.lineParamDeal(this.selectedRow);
	}
	checkAbnormal(row: any) {
        this.abnormalDeviceList = [];
        var Problem = {}
        for(var k=0;k< this.tableData.length;k++){
            if(this.tableData[k].id == row.id){
                this.tableData[k].isChecked = true
            }else{
                this.tableData[k].isChecked = false
            }
        }
        if(row.sensorProblemList && row.sensorProblemList.length > 0){
            for(var i=0;i<row.sensorProblemList.length;i++){
                Problem ={
                    "problem":row.sensorProblemList[i].sensorProblem,
                    "startTime": row.sensorProblemList[i].startTime,
                    "endTime": row.sensorProblemList[i].endTime,
                    "type": 1,
                    "isActive": false,
                    "deviceId": row.deviceId
                }
                this.abnormalDeviceList.push(Problem);
            }
            
        }
        if(row.gpsProblemEntity&& row.gpsProblemEntity.gpsProblem){
            var problemName = "GPS-" + row.gpsProblemEntity.gpsProblem
            Problem ={
                "problem": problemName,
                "startTime": row.gpsProblemEntity.startTime,
                "endTime": row.gpsProblemEntity.endTime,
                "type": 2,
                "isActive": false,
                "deviceId": row.deviceId
            }
            this.abnormalDeviceList.push(Problem);
        }
        this.abnormalCarNamber = row.carNumber;
        this.abnormalompanyName = row.companyName;
        this.abnormalDeviceList[0].isActive = true;
        console.log(this.abnormalDeviceList);

		// row对象新增属性
		this.activeSelected = row.id;
		this.startTime_chart = this.abnormalDeviceList[0].startTime;
		this.endTime_chart = this.abnormalDeviceList[0].endTime;
		this.isChartView = true;
		this.specifyTime = {
			startTime: this.startTime_chart,
			endTime: this.endTime_chart,
		}
		this.lineParamDeal(row);
	}
	runParent(value) {
		this.drawTrackArr = value;
	}
	//折线图时间回调事件
	getSelectChartTime(time) {
		this.startTime_chart = time.startTime;
		this.endTime_chart = time.endTime;
	}
	showMapView(val) {
		this.isMapView = val;
	}
	//获取传感器通道参数
	lineParamDeal(row) {
		let reqdata = 'deviceId=' + row.deviceId;
		this.jsonApiService.http("realtime/getRealTimeData.html", reqdata).subscribe(result => {
			if (result.success && result.data) {
				let params = {
					deviceId: row.deviceId,
					startTime: this.startTime_chart,
					endTime: this.endTime_chart,
					coefficient: result.data.coef,
				}
				this.selectedRow = params;
			}
		})
	}
	closeChart() {
        this.isChartView = false;
        for(var k=0;k< this.tableData.length;k++){
            this.tableData[k].isChecked = false
        }
    }
    DeviceListClick(item){
        for(var i=0;i<this.abnormalDeviceList.length;i++){
            if(item.problem == this.abnormalDeviceList[i].problem){
                this.abnormalDeviceList[i].isActive = true;
                this.startTime_chart = this.abnormalDeviceList[i].startTime;
                this.endTime_chart = this.abnormalDeviceList[i].endTime;
                this.specifyTime = {
                    startTime: this.startTime_chart,
                    endTime: this.endTime_chart,
                }
                this.lineParamDeal(this.abnormalDeviceList[i]);
            }else{
                this.abnormalDeviceList[i].isActive = false;
            }
        }
    }
}